package cn.lilyssh.order.provider.service;

import cn.lilyssh.common.kafka.provider.KafkaSender;
import cn.lilyssh.order.api.model.request.OrderInsertReq;
import cn.lilyssh.order.api.model.request.OrderQueryReq;
import cn.lilyssh.order.api.model.response.OrderQueryResp;
import cn.lilyssh.order.api.service.OrderServiceApi;
import cn.lilyssh.order.provider.dao.entity.OrderEntity;
import cn.lilyssh.order.provider.dao.repository.OrderRepository;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
@Component
@AllArgsConstructor
public class OrderService implements OrderServiceApi {

    private OrderRepository orderRepository;
    private KafkaSender kafkaSender;

    /**
     * 根据条件从数据库中查询订单列表
     * @param orderQueryReq
     * @return
     */
    @Override
    public List<OrderQueryResp> list(OrderQueryReq orderQueryReq){
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        if(null!=orderQueryReq){
            if(!StringUtils.isEmpty(orderQueryReq.getUserId())){
                qw.eq("user_id",orderQueryReq.getUserId());
            }
            if(!StringUtils.isEmpty(orderQueryReq.getShippingName())){
                qw.like("shipping_name",orderQueryReq.getShippingName());
            }
        }
        List<OrderEntity> orderEntityList = orderRepository.list(qw);
        List<OrderQueryResp> resultList=new ArrayList<>();
        orderEntityList.forEach(orderEntity->{
            OrderQueryResp  orderQueryResp=new OrderQueryResp();
            BeanUtils.copyProperties(orderEntity,orderQueryResp);
            resultList.add(orderQueryResp);
        });
        return resultList;
    }

    @Override
    public List<OrderQueryResp> latestOrder() {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();

        qw.orderByDesc("id");
        qw.last("limit 2");

        List<OrderEntity> orderEntityList = orderRepository.list(qw);
        List<OrderQueryResp> resultList=new ArrayList<>();
        orderEntityList.forEach(orderEntity->{
            OrderQueryResp  orderQueryResp=new OrderQueryResp();
            BeanUtils.copyProperties(orderEntity,orderQueryResp);
            resultList.add(orderQueryResp);
        });
        return resultList;
    }

    @Override
    public boolean save(OrderInsertReq orderInsertReq){
        OrderEntity  orderEntity=new OrderEntity();
        BeanUtils.copyProperties(orderInsertReq,orderEntity);
        return orderRepository.save(orderEntity);
    }

    @Override
    public boolean saveBatch(List<OrderInsertReq> orderInsertReqList) {
        List<OrderEntity> orderEntityList = new ArrayList<>();
        orderInsertReqList.forEach(orderInsertReq -> {
            OrderEntity orderEntity = new OrderEntity();
            BeanUtils.copyProperties(orderInsertReq,orderEntity);
            orderEntityList.add(orderEntity);
        });
        return orderRepository.saveBatch(orderEntityList);
    }

    /**
     * 根据条件从ES中查询订单列表
     * @param orderQueryReq
     * @return
     */
//    @Override
//    public List<OrderQueryResp> listByEs(OrderQueryReq orderQueryReq) {
//        SearchQuery searchQuery = new NativeSearchQuery(
//                new BoolQueryBuilder()
//                        .must(QueryBuilders.matchQuery("id",orderQueryReq.getId()))
//        );
//        Page<OrderESEntity> orderEntityPage = orderESRepository.search(searchQuery);
//        List<OrderESEntity> orderEntityList = orderEntityPage.getContent();
//        List<OrderQueryResp> orderQueryRespList=new ArrayList<>();
//        for (OrderESEntity orderEntity: orderEntityList) {
//            OrderQueryResp orderQueryResp=new OrderQueryResp();
//            BeanUtils.copyProperties(orderEntity,orderQueryResp);
//            orderQueryRespList.add(orderQueryResp);
//        }
//        return orderQueryRespList;
//    }

    /**
     * 保存到ESsaveBy
     * @param orderInsertReq
     * @return
     */
//    @Override
//    public boolean saveByEs(OrderInsertReq orderInsertReq){
//        OrderESEntity orderESEntity = new OrderESEntity();
//        BeanUtils.copyProperties(orderInsertReq,orderESEntity);
//        orderESRepository.save(orderESEntity);
//        return true;
//    }

    /**
     * 保存到kafka
     * @param orderInsertReq
     * @return
     */
    @Override
    public void saveByKafka(OrderInsertReq orderInsertReq){
        OrderEntity orderEntity=new OrderEntity();
        //直接写入数据库太慢，引起dubbo超时，导致调用多次，此处需要改造成kafka异步写入。
        BeanUtils.copyProperties(orderInsertReq,orderEntity);
        kafkaSender.send("placeOrder", orderEntity.getUserId().toString(), orderEntity);

//        System.out.println("预备备！开始！");
//
//        Timer timer = new Timer();
//        timer.schedule(new MyTask(timer), 0, 2000);  //任务等待0秒后开始执行，之后每2秒执行一次
    }

//    class MyTask extends TimerTask {
//        private Timer timer;
//        public MyTask(Timer timer) {
//            this.timer = timer;
//        }
//
//        int second = 0;
//        public void run() {
//            System.out.println("~~~第"+second+"秒~~~");
//            for (int i = 0; i < 500; i++) {
//                AddOrder addOrder=new AddOrder();
//                Thread thread=new Thread(addOrder);
//                thread.start();
//            }
//            second++;
//            if( second == 30){
//                this.timer.cancel();
//                System.out.println("#### 程序结束 ####");
//            }
//        }
//    }
//    class AddOrder implements Runnable{
//        @Override
//        public void run() {
//            OrderEntity orderEntity = new OrderEntity();
//            orderEntity.setUserId(753);
//            orderEntity.setPayment(new BigDecimal(928.23));
//            orderEntity.setCreateTime(new Date());
//            kafkaSender.send("placeOrder", orderEntity.getUserId().toString(), orderEntity);
//        }
//    }


}
